<?php


namespace api\crm\controller;


use api\crm\model\ActivityModel;
use api\crm\model\ApiActionLogModel;
use api\crm\model\CityModel;
use api\crm\model\CustomerStatusModel;
use api\crm\model\UserModel;
use api\crm\model\WechatUserModel;
use api\crm\model\WechatUserPointsLogModel;
use api\crm\model\ZhuanhuaModel;
use app\admin\model\AuthAppidModel;
use app\admin\model\OrderInfoModel;
use app\admin\model\TempUserRelationModel;
use cmf\controller\RestBaseController;
use Overtrue\Socialite\User;
use plugins\wechat\model\CacheModel;
use plugins\wechat\model\GetCardLogModel;
use plugins\wechat\model\WechatMenusModel;
use plugins\wechat\WechatPlugin;
use think\Db;
use think\facade\Env;
use function GuzzleHttp\Promise\all;

class WechatController extends RestBaseController
{
    public function menus()
    {
        $admin_id = cmf_get_current_admin_id();
        $admin_info = UserModel::get($admin_id);
        $result = WechatMenusModel::where('company_id', $admin_info['company_id'])->value('menu');
        $menus = json_decode($result);
        //{"button":[{"type":"view","name":"幸福厨房","sub_button":[{"type":"view","name":"厨Fun研究所","url":"https://mp.weixin.qq.com/mp/homepage?__biz=MzI2ODg2MDIyOQ==&hid=1&sn=445ee2d9964c1db972537c37dcfc911e"},{"type":"view","name":"装修小知识","url":"https://mp.weixin.qq.com/mp/homepage?__biz=MzI2ODg2MDIyOQ==&hid=3&sn=1d11607ce0df67be29826e6bc682cd00"},{"type":"view","name":"美食指南","url":"https://hsadmin.fotile.com/h5happylife/subject/detail.html?id=19"}],"url":"http://crmhtml.test2.zhicaisoft.cn/index.html?id=1"},{"type":"view","name":"商城入口","sub_button":[{"type":"view","name":"样机特惠","url":"http://crmhtml.test2.zhicaisoft.cn/store/index.html?id=1"},{"type":"view","name":"换装服务","url":"https://www.fotile.com/huanzhuang?site_id=6&cate=8&utm_source=fotile-xinmeiti-weixin-caidanlan0924"},{"type":"view","name":"活动直通车","url":"http://crmhtml.test2.zhicaisoft.cn/activity/index.html?id=1"},{"type":"view","name":"商城主界面","url":"http://crmhtml.test2.zhicaisoft.cn/store/index.html?id=1"},{"type":"view","name":"直播入口","url":"http://crmhtml.test2.zhicaisoft.cn/weixinlive/html/live/live_list.html?id=1"}],"url":""},{"type":"view","name":"CRM系统","sub_button":[],"url":"http://crmhtml.test2.zhicaisoft.cn/?id=1"}]}
        $menus = $menus ? $menus : json_decode('{"button":[]}');
        $this->success('获取微信菜单', ['menu' => $menus, 'admin_id' => $admin_id]);
    }

    public function test()
    {
        $data = $this->request->param();
//
//        $res = $this->validate($data,'Customer');
//        $user_list = UserModel::where(['customer_status' => 15])
//            ->field('id,company_id,customer_status,true_name,create_time')
//            ->order('create_time desc')
//            ->select()
//            ->each(function ($item) {
//                $yy_status = CustomerStatusModel::where(['name' => '意向客户', 'company_id' => $item['company_id']])->value('id');
//                if ($yy_status != $item['customer_status']) {
//                    UserModel::where('id', $item['id'])->update(['customer_status' => $yy_status]);
//                }
//                $item['status_aa'] = $yy_status;
//                return $item;
//            });
//        $user_list = hook('get_open_plat_form_url', $param = '');
        $user_list = ApiActionLogModel::all();
        $this->success('', ['info' => $user_list]);
    }

    public function get_jssdk()
    {
        $data = $this->request->param();
        $id = isset($data['id']) && $data['id'] ? $data['id'] : 0;
        $zt = isset($data['zt']) && $data['zt'] ? $data['zt'] : 0;
        $zp = isset($data['zp']) && $data['zp'] ? $data['zp'] : 0;
        $url = 'http://crmhtml.test2.zhicaisoft.cn/views/addRecord.html?id=' . $id . '&zt=' . $zt . '&zp=' . $zp;
        if (isset($data['return_url'])) {
            $return_url = $data['return_url'];
        } else {
            $return_url = $url;
        }

        $params['url'] = $return_url;
        $user_info = UserModel::get($id);
        $params['company_id'] = $user_info['company_id'];
        $js = hook('get_jssdk', $params);
        $this->success('js', $js);
    }

    public function get_address_by_location()
    {
        $data = $this->request->param();
        $mapx = isset($data['mapx']) && $data['mapx'] ? $data['mapx'] : 0;
        $mapy = isset($data['mapy']) && $data['mapy'] ? $data['mapy'] : 0;
        $url = "https://apis.map.qq.com/ws/geocoder/v1/?location=" . $mapy . "," . $mapx . "&key=L6DBZ-ZIGYW-JKQRR-OXY2S-67UTT-75FPC&get_poi=1";
        $res = file_get_contents($url);
        $res = json_decode($res)->result->pois;
        if ($res) {
            $result['address'] = $res[0]->address;
        } else {
            $result['address'] = '未获取到地址';
        }
        $this->success('获取地址', $result);
    }
    
    
    public function get_user_info()
    {
        $data = $this->request->param();
        $params['company_id'] = $data['id'];

        $params['return_url'] = isset($data['return_url']) && $data['return_url'] ? urlencode($data['return_url']) : '';
        $params['user_id'] = isset($data['user_id']) && $data['user_id'] ? $data['user_id'] : 0;

        if (isset($data['parent_id']) && !empty($data['parent_id'])) {
            $params['parent_id'] = $data['parent_id'];
        }
//        $this->success('aa', $params);
        $res = hook('wechat_config', $params);
        $this->success('aa', $res);
    }

    public function oauth_callback()
    {
        $data = $this->request->param();
        $params['company_id'] = $data['id'];
        $params['return_url'] = isset($data['return_url']) && $data['return_url'] ? $data['return_url'] : '';
        $params['user_id'] = isset($data['user_id']) && $data['user_id'] ? $data['user_id'] : 0;
        $params['parent_id'] = isset($data['parent_id']) && $data['parent_id'] ? $data['parent_id'] : 0;
        $user = hook('wechat_user', $params);
        $openid = $user[0]['original']['openid'];
        if ($params['user_id']) {
            $model = UserModel::get($params['user_id']);
            if (empty($model['openid'])) {
                $model->openid = $openid;
                $model->save();
            }
        }
        $user_model = WechatUserModel::where('openid', $openid)->find();
        if (empty($user_model)) {
            $user_model = new WechatUserModel([
                'openid' => $user[0]['original']['openid'],
                'nickname' => $user[0]['original']['nickname'],
                'headimgurl' => $user[0]['original']['headimgurl'],
                'sex' => $user[0]['original']['sex'],
                'city' => $user[0]['original']['city'],
                'province' => $user[0]['original']['province'],
                'language' => $user[0]['original']['language'],
                'country' => $user[0]['original']['country'],
                'company_id' => $data['id'],
                'member_no' => create_member_no(),
            ]);
        } else {
            $user_model->nickname = $user[0]['original']['nickname'];
            $user_model->headimgurl = $user[0]['original']['headimgurl'];
            $user_model->sex = $user[0]['original']['sex'];
            $user_model->city = $user[0]['original']['city'];
            $user_model->province = $user[0]['original']['province'];
            $user_model->language = $user[0]['original']['language'];
            $user_model->country = $user[0]['original']['country'];
            if (empty($user_model['member_no'])) {
                $user_model->member_no = create_member_no();
            }
        }
        $user_model->save();

        $search = WechatUserModel::where('openid', $openid)->find(); //被推荐人

        $get = ZhuanhuaModel::where('parent_id', $params['parent_id'])->where('uid', $search['id'])->find();

        if (!$get && empty($search['parent_id'])) {
            // 存在推荐人的话
            if (isset($params['parent_id']) && !empty($params['parent_id'])) {
                $find = WechatUserModel::where('id', $params['parent_id'])->find();// 推荐人

                if ($search['company_id'] == $find['company_id']) {
                    //开始事务
                    Db::startTrans();
                    try {
                        $count = ZhuanhuaModel::where('parent_id', $params['parent_id'])->count();
                        $depp = $count + 1;
                        // 转化日志
                        $log = new ZhuanhuaModel([
                            'parent_id' => $params['parent_id'],
                            'uid' => $search['id'],
                            'depp' => $depp,
                            'created_at' => time()
                        ]);
                        if (!$log->save()) {
                            throw new \Exception('网络错误请稍后重试！');
                        }
                        // 用户表更新推荐人id
                        $user = WechatUserModel::get($search['id']);
                        $user->parent_id = $params['parent_id'];
                        if (!$user->save()) {
                            throw new \Exception('网络错误请稍后重试！');
                        }

                        // 提交事务
                        Db::commit();
                    } catch (\Exception $e) {
                        // 回滚事务
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                }
            }
        }

        if ($params['return_url']) {
            $url = $params['return_url'] . '&openid=' . $openid;
        } else {
            $url = 'http://crmhtml.test2.zhicaisoft.cn/test.html?openid=' . $openid;
        }
        header('Location:' . $url);
    }


    public function send_message()
    {
        $params['company_id'] = 1;
        $params['openid'] = 'oRdnWwhhnQiNotHmpYCV7_S_KhLs';
        $params['template_id'] = '1SUA3v9FbuTox9C8a4L3W1KF_nonZ4Tmkf4TDuUg-aU';
        $params['url'] = 'http://www.baidu.com';
        $params['data'] = [
            'first' => '内容',
            'keyword1' => '11',
            'keyword2' => '222',
            'keyword3' => '333',
            'keyword4' => date('Y-m-d H:i:s', time()),
            'remark' => '测试'
        ];
        $res = hook('send_template_message', $params);
        $this->success('ok', $res);
    }

    public function ceshi()
    {
        $user_info = WechatUserModel::where('openid', 'oRdnWwvMvP2Be4s14ItV5U89bz34')->find();
        $param['card_id'] = 'pRdnWwipTJdOv38m0cS3o9FSwHUw';
        $param['company_id'] = $user_info['company_id'];
        $param['code'] = 226050130703;
        $result = hook('get_member_user_info', $param);

        //var_dump($user_info['company_id']);die;
        //var_dump($result);die;


        $obj = new WechatPlugin();

        $res = $obj->update_card_info([
            'company_id' => 1,
            'user_id' => 25,
            'cardId' => 'pRdnWwipTJdOv38m0cS3o9FSwHUw',
            'code' => '226050130703',
            'bonus' => '1',
        ]);

        var_dump($res);

    }
}
